import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Form, Select, Table, Empty, Modal, message } from 'antd';
import TPage from '@/modules/TPage';
import CreateModal from './modules/CreateModal';
import { YesOrNo } from '@/public/constant/enums';
import Service from '@/public/http/services';
import { ScopeStyle } from '@/public/constant/enums';
import style from './index.css';
const { Option } = Select;
const { Column } = Table;
const List: React.FC<any> = ({ total, list, dispatch }) => {
  const [curPage, setCurPage] = useState(1);
  const [curName, setCurName] = useState(null);
  const pageSize = 10;
  /**
   * 加载列表数据
   */
  function fetchList({ page, name }) {
    dispatch({
      type: 'kindergarten_list/fetchList',
      payload: {
        page,
        name,
        pageSize
      }
    })
  }

  /**
   * @desc 操作完更新列表
   */
  function reFetchList() {
    fetchList({
      page: curPage,
      name: curName
    })
  }

  useEffect(({ page = curPage, name = curName } = {}) => {
    fetchList({ page, name })
  }, [curPage, curName])
  // 渲染列表查询表单

  const handleQuery = (query) => {
    setCurPage(1);
    setCurName(query);
  }

  function renderTableForm() {
    const WrappedForm = Form.create<any>({ name: 'tableForm' })(function ({ form }) {
      const { getFieldDecorator } = form as any;
      return (
        <Form onSubmit={handleQuery.bind(null, form)} layout={'inline'}>
        </Form>
      );
    })
    return (
      <WrappedForm />
    );
  }

  // 根据渲染类型渲染列表
  const renderActions =
    (record: any) => {
      return (
        <>
          {/* <Button className={style.mr8} type={'primary'} onClick={() => { handleEdit(record) }}>编辑</Button> */}
          {/* <Button className={style.mr8} type={'primary'} onClick={() => { handleEdit(record) }}>查看详情</Button> */}
        </>
      );
    }
  const [formModalVisible, setFormModalVisible] = useState(false);
  const [curModalStatus, setCurModalStatus] = useState(0);

  /**
   * 
   * @desc 创建
   */
  const handleCreate = () => {
    setCurModalStatus(0);
    setFormModalVisible(true);
  }

  const [curEditInfo, setCurEditInfo] = useState({})
  /**
   * 
   * @desc 编辑
   */
  const handleEdit = (record) => {
    setCurModalStatus(1);
    setCurEditInfo(record);
    setFormModalVisible(true);
  }

  /**
   * @desc 创建提交
   */
  const handleSubmit = (form: any, { files, logos }, type) => {
    const { validateFields, resetFields } = form;
    validateFields((err, value) => {
      if (!err) {
        const { chargeUsername,
          location,
          name,
          personnelScale,
          remark,
          tel } = value;
        const params = {
          logoPic: (logos[0] as any).url,
          coverPic: (files[0] as any).url,
          chargeUsername,
          location,
          name,
          personnelScale,
          remark,
          tel
        };
        (type ? Service.createOrg(params) : Service.updateOrg({ id: curEditInfo['id'], ...params })).then(() => {
          message.info(`${type ? '添加' : '修改'}成功`);
          resetFields();
          setCurEditInfo({});
          setFormModalVisible(false);
          reFetchList();
        })
      }
    })
  }

  /**
   * 
   * @desc 创建/编辑取消
   */
  const handleCancel = (form) => {
    form.resetFields();
    setCurEditInfo({});
    setFormModalVisible(false);
  }

  return (
    <TPage>
      <TPage.Title>园所列表</TPage.Title>
      <TPage.Table>
        <TPage.Search
          placeholder={'请输入园所名称，可按回车键搜索'}
          onSearch={handleQuery}
        />
        <TPage.Layout>
          {renderTableForm()}
        </TPage.Layout>
        {/* <TPage.Layout className={style.btns}>
          <Button type={'primary'} onClick={handleCreate}>新建</Button>
        </TPage.Layout> */}
        <Table
          className={classnames(style.mt16, style.kindergarten_list)}
          locale={{ emptyText: <Empty description={'无数据'} /> }}
          dataSource={list}
          pagination={{ total, current: curPage, pageSize, onChange: setCurPage }}
          rowKey={(record: any) => record.id}
          scroll={{ x: 1500 }}
        >
          <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
          <Column title={'园所名称'} key={'name'}
            render={(value, record: any) => {
              return <span className={style.thumbnail}>
                < img src={record.logoPic} />
                {record.name}
              </span>
            }}
          />
          <Column title={'人员规模'} dataIndex={'personnelScale'} key={'scope'} render={(value) => <span style={ScopeStyle[value]}>{value}</span>}/>
          <Column title={'是否为名园'} dataIndex={'isFamous'} key={'isFamous'} render={(value) => <span className={style[+value === 1 ? 'active' : 'default']}>{YesOrNo[value || '0']}</span>}/>
          <Column title={'董事长'} dataIndex={'chargeUsername'} key={'manager'} />
          <Column title={'联系方式'} dataIndex={'tel'} key={'tel'} />
          <Column title={'获赞数'} dataIndex={'starNum'} key={'starNum'} />
          <Column title={'备注'} dataIndex={'remark'} key={'remark'} />
          <Column title={'创建时间'} dataIndex={'cTime'} key={'cTime'} render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          {/* <Column title={'操作'} key={'act'} render={renderActions} /> */}
        </Table>
      </TPage.Table>
      <CreateModal visible={formModalVisible}
        title={curModalStatus === 0 ? '机构创建' : '机构编辑'}
        formData={curModalStatus === 0 ? {} : curEditInfo}
        onOK={(form, data) => handleSubmit(form, data, curModalStatus === 0)}
        onCancel={handleCancel} />
    </TPage>
  );
}
export default connect((state: any) => {
  return {
    list: state.kindergarten_list.list,
    total: state.kindergarten_list.total,
  };
})(List);